//
//  LoginViewController.m
//  RS.Fruit.IOS
//
//  Created by zhaiqiuqiu on 16/10/24.
//  Copyright © 2016年 com.rs. All rights reserved.
//

#import "LoginViewController.h"
#import "ShelterView.h"
#import "MainViewController.h"
#import "DoImagePickerController.h"
#import "RSWDataOperation+Login.h"

#define CELL_H 44
#define CELL_IMAGE_SIZE 22
#define CELL_TEXT_SIZE 16
#define SUBITEM_H 36
#define ABOUT_BUTTON_H 30

@interface LoginViewController ()<UITextFieldDelegate,XUIButtonDelegate,ShelterViewDelegate>
{
    UIView *_userInfoInputView;
    UITextField *_userNameField;
    UITextField *_passwordField;
    
    XUIButton *_loginBtn;
    XUIButton *_forgotBtn;
    
    XUISelector *_selector;
    
    UISegmentedControl *_seg;
    
    RSWDataOperation *_um;
    
    NSDictionary *_userConfig;
    
    UIProgressView *_progressView;
    
    UILabel *_progressLabel;
    
    UIView *_inputPanelView;
    
    UIView *_progressPanelView;
}
@end

@implementation LoginViewController

- (void)dealloc
{
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[XUINavigationController navigationController] setNavigationBarHidden:YES animated:YES];
}

- (void)viewDidLoad {
    //[[XUINavigationController navigationController] setNavigationBarHidden:YES animated:YES];
    
    NSString *path = [[XMSFileHelper documentPath] stringByAppendingPathComponent:SYSCFGFE];
    [XLGContext loadSyscfgplist:path];
    
    [CRequestChannelPoolShell startRequestRunLoop];
    
    _um = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    
    NSString *szPath = [NSString pathWithComponents:[NSArray arrayWithObjects:[XMSFileHelper documentPath], [XLGContext context].m_dicLastuser[XLGContextLastUserInfo][XLGContextLastUserInfoUserNum], USERCFGFE, nil]];
    _userConfig = [NSMutableDictionary dictionaryWithContentsOfFile:szPath];
    
    //登陆界面背景
    self.view.backgroundColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStylef1f4f7Color];
    
    float statusBarH = [UIApplication sharedApplication].statusBarFrame.size.height;
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(113*kWidthScale, 67*kHeightScale, [UIDevice screenWidth] -  113*kWidthScale*2, 97*kHeightScale)];
    bgImageView.contentMode = UIViewContentModeScaleAspectFit;
    if (![UIDevice isIOS7OrNewer])
        bgImageView.top -= statusBarH;
    
    bgImageView.image = [UIImage imageNamed:@"img_logo"];
    
    [self.view addSubview:bgImageView];
    
    _inputPanelView = [[UIView alloc]initWithFrame:self.view.bounds];
    _inputPanelView.alpha = 0;
    [self.view addSubview:_inputPanelView];
    
    _progressPanelView = [[UIView alloc]initWithFrame:self.view.bounds];
    _progressPanelView.alpha = 0;
    [self.view addSubview:_progressPanelView];
    
    _userInfoInputView = [[UIView alloc]initWithFrame:CGRectMake(43*kWidthScale, 0, [UIDevice screenWidth] - 43*kWidthScale*2, 2*CELL_H*kHeightScale+10*kHeightScale)];
    _userInfoInputView.backgroundColor = [UIColor clearColor];
    _userInfoInputView.top = bgImageView.bottom  + 40*kHeightScale;
    [_inputPanelView addSubview:_userInfoInputView];
    
    _userNameField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, _userInfoInputView.width, CELL_H*kHeightScale)];
    _userNameField.delegate = self;
    _userNameField.textInputMaxLength = 13;
    _userNameField.placeholder = @"帐号";
    _userNameField.returnKeyType = UIReturnKeyNext;
    //_userNameField.keyboardType = UIKeyboardTypeDefault;
    _userNameField.font = [UIFont systemFontOfSize:15];
    _userNameField.backgroundColor = [UIColor whiteColor];
    _userNameField.autocorrectionType=UITextAutocorrectionTypeNo;
    _userNameField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _userNameField.borderStyle = UITextBorderStyleNone;
    _userNameField.layer.borderColor=[[UIColor colorWithHex:mcrmSAASUISkinColorTextStyleddddddColor] CGColor];
    _userNameField.layer.borderWidth= 0.5f;
    _userNameField.layer.cornerRadius = 2;
    _userNameField.layer.masksToBounds = YES;
    _userNameField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    
    [self.view addSubview:_userInfoInputView];
    UIImageView *leftImage1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"img_login_user"]];
    leftImage1.contentMode = UIViewContentModeScaleAspectFit;
    leftImage1.frame = CGRectMake(15*kWidthScale, 15*kWidthScale, 15*kWidthScale*3, 15*kWidthScale);
    
    [_userNameField setLeftViewMode:UITextFieldViewModeAlways];
    [_userNameField setLeftView:leftImage1];
    
    _userNameField.text = [XLGContext context].m_dicLastuser[XLGContextLastUserInfo][[XLGContext context].m_dicLastuser[XLGContextLastUserDisplayKey]];
    [_userInfoInputView addSubview:_userNameField];

    _passwordField = [[UITextField alloc]initWithFrame:CGRectMake(0, _userNameField.bottom+10*kHeightScale, _userInfoInputView.width, CELL_H*kHeightScale)];
    _passwordField.delegate = self;
    _passwordField.secureTextEntry = YES;
    _passwordField.textInputMaxLength = 16;
    _passwordField.placeholder = @"密码";
    _passwordField.returnKeyType = UIReturnKeyGo;
    _passwordField.font = [UIFont systemFontOfSize:15];
    _passwordField.backgroundColor = [UIColor whiteColor];
    _passwordField.autocorrectionType=UITextAutocorrectionTypeNo;
    _passwordField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _passwordField.borderStyle = UITextBorderStyleNone;
    _passwordField.layer.borderColor=[[UIColor colorWithHex:mcrmSAASUISkinColorTextStyleddddddColor] CGColor];
    _passwordField.layer.borderWidth= 0.5f;
    _passwordField.layer.cornerRadius = 2;
    _passwordField.layer.masksToBounds = YES;
    _passwordField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    
    UIImageView *leftImage2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"img_login_lock"]];
    leftImage2.contentMode = UIViewContentModeScaleAspectFit;
    leftImage2.frame = CGRectMake(15*kWidthScale, 15*kWidthScale, 15*kWidthScale*3, 15*kWidthScale);
    
    [_passwordField setLeftViewMode:UITextFieldViewModeAlways];
    [_passwordField setLeftView:leftImage2];
    
    if(((NSString*)[XLGContext context].m_dicLastuser[XLGContextLastUserInfo][XLGContextLastUserInfoUserNum]).length > 0)
    {
        BOOL b = [_userConfig[XLGUserConfigDefaultKeySavePassword] boolValue];
        if(b == YES)
        {
            NSString *szPath = [NSString stringWithFormat:@"%@/%@/%@", [XMSFileHelper documentPath], [XLGContext context].m_dicLastuser[XLGContextLastUserInfo][XLGContextLastUserInfoUserNum], PSWF];
            _passwordField.text =  [_um localPassword:szPath];
        }
    }

    [_userInfoInputView addSubview:_passwordField];
    
    //记住密码
    _selector = [[XUISelector alloc]initWithFrame:CGRectMake(10*kWidthScale, _userInfoInputView.bottom + 9*kHeightScale, 0 , 0) title:@"记住密码" headImage:[UIImage imageNamed:@"img_password_uncheck"] highlightedImage:[UIImage imageNamed:@"img_password_check"]];
    _selector.titleLabel.font = [UIFont systemFontOfSize:12];
    _selector.titleLabel.textColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStyle83838dColor];
    _selector.size = [_selector fitSize];
    _selector.right = _userInfoInputView.right;
    [_selector setSelected:_userConfig != nil ? [_userConfig[XLGUserConfigDefaultKeySavePassword]boolValue] : YES animated:NO];
    [_selector addTarget:self action:@selector(clickSavePassword:) forControlEvents:UIControlEventTouchUpInside];
    //[_inputPanelView addSubview:_selector];
    
    //登入按钮
    _loginBtn = [XUIButton buttonWithStyleType:XUIButtonStyleTypeCustom delegate:self];
    _loginBtn.frame = CGRectMake(43*kWidthScale, _selector.bottom + 20*kHeightScale, [UIDevice screenWidth] - 43*kWidthScale*2, CELL_H*kHeightScale);
    [_loginBtn SetTitle:@"登录"];
    [_loginBtn SetTextAlignment:NSTextAlignmentCenter];
    _loginBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [_loginBtn SetTitleColor:[UIColor whiteColor]];
    _loginBtn.layer.cornerRadius = 2;
    _loginBtn.layer.masksToBounds = YES;
    _loginBtn.backgroundColor = [UIColor colorWithHex:mcrmSAASUIShinColorTextStyle2196F3Color];
    [_inputPanelView addSubview:_loginBtn];
    
    //版本号
    UILabel *vLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 20*kWidthScale, 20*kHeightScale)];
    vLabel.bottom = self.view.bottom-10*kHeightScale;
    vLabel.backgroundColor = [UIColor clearColor];
    vLabel.font = [UIFont systemFontOfSize:11];
    vLabel.textColor = [UIColor colorWithR:155 G:155 B:155 A:1.0];
    vLabel.textAlignment = NSTextAlignmentCenter;
    //vLabel.text = [NSString stringWithFormat:@"V %@",[XLGContext context].m_szVersionname];
    vLabel.text = [NSString stringWithFormat:@"润石科技智慧政务%@版本",@"演示"];
    vLabel.width = [vLabel.text stringSizeWithFont:vLabel.font].width;
    vLabel.centerX = self.view.centerX;
    [_inputPanelView addSubview:vLabel];
    
    //登入进度条
    _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
    _progressView.frame = CGRectMake(20,self.view.height / 2 -50,self.view.width - 20 - 20 ,5);
    [_progressPanelView addSubview:_progressView];
    
    //登入进度条下面显示的文字
    _progressLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, _progressView.bottom + 10, self.view.width - 10 - 10, 20)];
    _progressLabel.textAlignment = NSTextAlignmentCenter;
    _progressLabel.font = [UIFont systemFontOfSize:15];
    _progressLabel.text = @"帐号验证";
    [_progressPanelView addSubview:_progressLabel];
    
    if(((NSString*)[XLGContext context].m_dicLastuser[XLGContextLastUserLoginKey]).length > 0)
    {
        BOOL b = [_userConfig[XLGUserConfigDefaultKeyAutoLogin] boolValue];
        if(b == NO)
            goto funExit;
        
        b = [_userConfig[XLGUserConfigDefaultKeySavePassword] boolValue];
        if(b == NO)
            goto funExit;
        
        [self login:OfflineLoginTypeChangeOffline];
        
        return;
    }
    
funExit:
    [self hiddenInputPanelView:NO animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewControllerWillDealloc
{
    [super viewControllerWillDealloc];
}

#pragma mark --
#pragma mark -- textfield delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return YES;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [UIViewController closeKeyBoard];
}

#pragma mark --
#pragma mark -- customButtonEx delegate

-(CGRect)button:(XUIButton *)btn titleContentRect:(CGRect)rect
{
    return rect;
}

-(void)clickedUpInsideOfButton:(XUIButton *)btn
{
    [self beginLogin];
}

-(void)clickSavePassword:(XUISelector*)selector
{
}

#pragma mark --
#pragma mark -- presentSwitchViewController delegate

-(void)observerQuickExperienceExplainViewControllerQuickRegisterSuccessNotification:(NSNotification*)noti
{
    //[XUINavigationController pushReplaceViewControllerClass:[MainViewController class]];
}

#pragma mark --
#pragma mark -- login fun

-(void)beginLogin
{
    [UIViewController closeKeyBoard];

    if (_userNameField.text.length <= 0)
    {
        [UIAlertView showErrorMsg:@"请输入帐号"];
        
        return;
    }

    if (_userNameField.text.length > 0 && _passwordField.text.length <= 0)
    {
        [UIAlertView showErrorMsg:@"请输入密码"];
        return;
    }
    
    [self login:OfflineLoginTypeChangeOffline];
}

-(void)login:(OfflineLoginType)offlineLoginType
{
    [self hiddenInputPanelView:YES animated:YES];
    
    [_um loginByAccount:_userNameField.text password:_passwordField.text completion:^(NSInteger nResult, NSError *error)
     {
         if(nResult != YES)
             [self hiddenInputPanelView:NO animated:YES];
         
         switch(nResult)
         {
             case TRUE:
             {
                 [XLGUserConfig writeCurrentUserConfigWithDictionary:@{XLGUserConfigDefaultKeyAutoLogin:@(1),XLGUserConfigDefaultKeySavePassword:@(_selector.selected)}];
                 
                 [XLGContext saveFirstRun:NO];
                 
                 [XUINavigationController pushReplaceViewControllerClass:[MainViewController class]];
                 
                 break;
             }
            case PROTOCOLRETOBJNIL:
             {
                 switch (error.code)
                 {
                    default:
                     {
                         [UIAlertView showMessageWithTitle:@"登录失败" message:error.domain];
                         break;
                     }
                 }
                 break;
             }
             default:
             {
                 [UIAlertView showMessageWithTitle:@"登录失败" message:@"登录超时"];
                 break;
             }
         }
     }];
}

#pragma mark --
#pragma mark -- progress

- (void)hiddenInputPanelView:(BOOL)hidden animated:(BOOL)animated
{
    _progressView.progress = 0;
    
    if(animated == YES)
    {
        self.view.userInteractionEnabled = NO;
        
        [UIView animateWithDuration:0.3 animations:^
         {
             _userInfoInputView.alpha = !hidden;
             _inputPanelView.alpha = !hidden;
             _progressPanelView.alpha = hidden;
         } completion:^(BOOL finished)
         {
             self.view.userInteractionEnabled = YES;
         }];
    }
    else
    {
        _inputPanelView.alpha = !hidden;
        _progressPanelView.alpha = hidden;
    }
}

- (void)beginProgressView:(XMSDataOperationManager *)dom
{
    //    [self beginProgressViewPanel:@"正在为您加载数据，请稍候"];
}

- (void)loginStatus:(NSString *)szStatus
{
    DispatchMainThreadAsync(^
    {
        if([szStatus rangeOfString:RSWLoginOperationStartLoadBaseStatusTip].location != NSNotFound)
        {
            [_progressView setProgress:_progressView.progress + 0.1 animated:YES];
            _progressLabel.text = @"正在努力地加载数据";//@"初始化数据中";
        }
        else if([szStatus rangeOfString:RSWLoginOperationCheckVersionStatusTip].location != NSNotFound)
        {
            [_progressView setProgress:_progressView.progress + 0.1 animated:YES];
            _progressLabel.text = RSWLoginOperationCheckVersionStatusTip;
        }
        else if([szStatus rangeOfString:XLGLoginCommonProcessLoginingCheckAccountStatusTip].location != NSNotFound)
        {
            [_progressView setProgress:0 animated:YES];
            _progressLabel.text = @"帐号验证中";
        }
        else if([szStatus rangeOfString:RSWLoginOperationLoadAddressBookStatusTip].location != NSNotFound ||
                [szStatus rangeOfString:RSWLoginOperationLoadBaseDataDicStatusTip].location != NSNotFound||
                [szStatus rangeOfString:RSWLoginOperationLoadBaseDataMenuStatusTip].location != NSNotFound)
        {
            [_progressView setProgress:_progressView.progress + 0.1 animated:YES];
        }
        else if([szStatus rangeOfString:RSWLoginOperationFinishLoadBaseStatusTip].location != NSNotFound)
        {
            [_progressView setProgress:1 animated:YES];
        }
    });
}


- (BOOL)loginCheckLocalTimeLessThanServiceTime:(long long)serviceTime
{
    long long t = [[NSDate date] timeIntervalSince1970] - serviceTime;
    if( t > 60 * 10 /* - 10*/ || t < - 60 * 10 /* + 10*/)
        return NO;
    return YES;
}

#pragma mark --
#pragma mark -- shelterView

-(void)clickedCancelButtonOfShelterView:(ShelterView*)shelterView
{
    
}
-(void)clickedOtherButtonOfshelterView:(ShelterView*)shelterView
{
    [XMSCallTelephone callTelephone:@"400-100-0566"];
}

@end
